import java.util.concurrent.PriorityBlockingQueue;

//定时器
class Mytask implements Comparable<Mytask>{
    private Runnable runnable;
    // 定义任务执行时间
    private long time;

    public Mytask(Runnable runnable,long delay){
        if(runnable==null){
            try{
                throw new IllegalAccessException("任务不能为空");
            } catch (IllegalAccessException e) {
                throw new RuntimeException(e);
            }
        }
        if(delay<0){
            try {
                throw new IllegalAccessException("时间不能小于0");
            } catch (IllegalAccessException e) {
                throw new RuntimeException(e);
            }
        }
        this.runnable=runnable;
        //计算出任务的具体时间
        this.time=delay+System.currentTimeMillis();
    }

    public Runnable getRunnable() {
        return runnable;
    }

    public long getTime() {
        return time;
    }

    @Override
    public int compareTo(Mytask o) {
       if(this.getTime()-o.getTime()>0)return 1;
       else if(this.getTime()-o.getTime()==0)return 0;
       else return -1;
    }
}

public class MyTimer {
    //定义线程内容
   private PriorityBlockingQueue<Mytask> priorityBlockingQueue=new PriorityBlockingQueue<>();

   public MyTimer() {
       //扫描线程
       Thread th1 = new Thread (()-> {
           synchronized (this) {
               while (true) {
                   try {
                       Mytask take = priorityBlockingQueue.take();
                       //判断有没有到时间
                       long times = System.currentTimeMillis();
                       if (times >= take.getTime()) {
                           //时间到了执行任务
                           take.getRunnable().run();
                       } else {
                           long waittime = take.getTime() - times;
                           //没有到时间放回阻塞队列
                           priorityBlockingQueue.put(take);
                           //进行休眠
                           this.wait(waittime);
                       }
                   } catch (InterruptedException e) {
                       throw new RuntimeException(e);
                   }
               }
           }
       });
       th1.start();
   }
   public void schedule(Runnable runnable,long time) {
       //构建一个Mytask对象
       Mytask mytask=new Mytask(runnable,time);
       //放入阻塞数组
       priorityBlockingQueue.put(mytask);
       //唤醒等待线程
       synchronized (this){
           this.notifyAll();
       }
    }

}

